package priv.xakml.toolkit;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Md5Tookit extends HashBase{
    private String mEncoding = "UTF-8";
    public Md5Tookit() {
    }

    public Md5Tookit(String encoding) {
        mEncoding = encoding;
    }


    /**
     * 计算给定字符串的MD5值，结果以16进制的方式返回
     * 关于base64编码Encode和Decode编码的几种方式
     * https://www.cnblogs.com/alter888/p/9140732.html
     * @param source_content 需要计算MD5值的原始字符串
     * @return 计算后，以十六进制的字符串方式返回
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    public String computeHash(String source_content) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest m = MessageDigest.getInstance("MD5");
        byte[] source_data = source_content.getBytes(mEncoding);
        return computeHashToHexString(m, source_data);
    }



    /**
     *  计算指定数据的md5哈希值
     * @param source_data
     * @return
     * @throws NoSuchAlgorithmException
     */
    public byte[] computeHash(byte[] source_data) throws NoSuchAlgorithmException {
        MessageDigest m = MessageDigest.getInstance("MD5");
        m.update(source_data);
        byte[] result = m.digest();
        return result;
    }

    /**
     * 计算文件的MD5哈希值
     * @param file 文件
     * @return hash值(字节数组格式)
     * @throws IOException 文件不存在的异常
     * @throws NoSuchAlgorithmException 系统不支持此摘要算法
     */
    public byte[] computeHash(File file)throws IOException,NoSuchAlgorithmException {
        InputStream stream = Files.newInputStream(file.toPath(), StandardOpenOption.READ);
        MessageDigest digest = MessageDigest.getInstance("MD5");
        byte[] buf = new byte[8192];
        int len;
        while ((len = stream.read(buf)) > 0) {
            digest.update(buf, 0, len);
        }
        byte[] hash = digest.digest();
        return hash;
    }
}
